package com.dycong.common.network;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

/**
 * Created by dycong on 15-7-21.
 */
public class NetworkUtil {

    public static void fetchUrlSaveTo(String url, String fileToSave) {
        try {
            URL website = new URL(url);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(fileToSave);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } catch (Throwable e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new RuntimeException(e);
            }
        }
    }


    public static byte[] readFromImageUrl(String urlString) {
        try {
            URL url = new URL(urlString);

            // read image direct from url
            BufferedImage image = ImageIO.read(url);

            // write image to output stream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            baos.flush();

            // get bytes
            return baos.toByteArray();
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}
